/*
 * BackgroundImageShuffler - Wallpaper changer for Android
 * Copyright (C) 2011 Juhana Paavola <juhana.paavola@gmail.com>
 *
 * This file is part of BackgroundImageShuffler.
 *
 * BackgroundImageShuffler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * BackgroundImageShuffler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License
 * along with BackgroundImageShuffler.  If not, see <http://www.gnu.org/licenses/>.
*/
package com.juhanapaavola.widget;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.ToggleButton;

public class BISConfigure extends Activity {
	int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	SharedPreferences mPrefs;
	SharedPreferences.Editor mEditor;
	
	static String PREF_NAME="settings";
	static String PREF_ACTIVATED="PREF_ACTIVATED";
	static String PREF_FROM="PREF_FROM";
	static String PREF_RESIZE="PREF_RESIZE";
	static String PREF_FROM_SPINNER_INDEX="PREF_FROM_SPINNER_INDEX";
	static String PREF_USE_SCHEDULED="PREF_USE_SCHEDULED";
	static String PREF_USE_SCHEDULED_HOUR="PREF_USE_SCHEDULED_HOUR";
	static String PREF_USE_SCHEDULED_MINUTE="PREF_USE_SCHEDULED_MINUTE";
	static String PREF_SCALE_DOWN = "PREF_SCALE_DOWN";
	
	private boolean mActivated = false;
	private String mFromDir = Environment.DIRECTORY_PICTURES;
	private boolean mResize = false;
	private Resources mResources = null;
	private Spinner mFspinner = null;
	private Button mSaveButton = null;
	private CheckBox mResizeCheckbox = null;
	private CheckBox mScaleDownCheckBox = null;
	private ToggleButton mActiveToggleButton = null;
	private CheckBox mScheduleCheckBox = null;
	private TimePicker mScheduleTimePicker = null;
	private int mFromIndex = 0;
	private boolean mUseScheduled = false;
	private boolean mScaleDown = false;
	private Context mContext = null;
	private boolean mWasActive = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		 super.onCreate(savedInstanceState);
		 setResult(RESULT_CANCELED);

		 setContentView(R.layout.bisconfigure);
		 mContext = this;
		 
		 Intent intent = getIntent();
		 Bundle extras = intent.getExtras();
		 if (extras != null) {
			 mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
		 }

		 
		 if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
			 finish();
		 }
		 
		 BISProvider.cancelAlarmService(this);		 
		 
		 mPrefs = getSharedPreferences(PREF_NAME, 0);
		 mEditor = mPrefs.edit();
		 mResources = this.getResources();
		 
		 mWasActive = mPrefs.getBoolean(PREF_ACTIVATED, false);
		 
		 mActiveToggleButton = (ToggleButton)findViewById(R.id.activateToggleButton);
		 mActiveToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				mActivated = isChecked;
			}			 
		 }
		 );
		 		 
	
		 mFspinner = (Spinner)findViewById(R.id.getFromPathSpinner);
		 mFspinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItemView,
					int position, long id) {
				
				String item = (String)mFspinner.getSelectedItem();
				String[] array = mResources.getStringArray(R.array.getFromStrings);
								
				// 0 = all
				// 1 = all but not camera
				// 2 = camera
				if(item.equals(array[0])){
					mFromDir = BISService.FROM_ALL;
				}else if(item.equals(array[1])){
					mFromDir = BISService.FROM_NOTCAMERA;
				}else if(item.equals(array[2])){
					mFromDir = BISService.FROM_CAMERA;
				}				
				
				mFromIndex = position;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
				// TODO Auto-generated method stub
				
			}
		 });
		 
		 mSaveButton = (Button)findViewById(R.id.saveSettingsButton);
		 mSaveButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final Context context = BISConfigure.this;

				writeSettings();
				
		        // Push widget update to surface with newly set prefix
		        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		        BISProvider.updateAppWidget(context, appWidgetManager, mAppWidgetId);

		        // Make sure we pass back the original appWidgetId
		        Intent resultValue = new Intent();
		        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
		        setResult(RESULT_OK, resultValue);
		        finish();			 				
			}
		});

		 mScaleDownCheckBox = (CheckBox)findViewById(R.id.scaleDownCheckBox);
		 mScaleDownCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				mScaleDown = isChecked;				
			}
		});

		 mResizeCheckbox = (CheckBox)findViewById(R.id.fittoscreenCheckBox);
		 mResizeCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				mResize = isChecked;							
				mScaleDownCheckBox.setEnabled(mResize);
			}
		});

		 mScheduleCheckBox = (CheckBox)findViewById(R.id.useScheduledCheckBox);
		 mScheduleCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				mUseScheduled = isChecked;
				setChangeText(mUseScheduled);
			}
		});

		 Button about = (Button)findViewById(R.id.aboutButton);
		 about.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Builder dialog = new AlertDialog.Builder(mContext);
				dialog.setTitle(R.string.about);
				dialog.setMessage(R.string.about_text);
				dialog.setPositiveButton("OK", null);
				dialog.show();
			}
		});
		 
		 mScheduleTimePicker = (TimePicker)findViewById(R.id.scheduleTimePicker);
		 
		 // set values from preferences
		 mActiveToggleButton.setChecked(mPrefs.getBoolean(PREF_ACTIVATED, false));
		 boolean resize = mPrefs.getBoolean(PREF_RESIZE, false);
		 mResizeCheckbox.setChecked(resize);
		 mFspinner.setSelection(mPrefs.getInt(PREF_FROM_SPINNER_INDEX, 0));
	 
		 
		 mScaleDownCheckBox.setEnabled(resize);
		 mScaleDownCheckBox.setChecked(mPrefs.getBoolean(PREF_SCALE_DOWN, false));
		 
		 
		 mUseScheduled = mPrefs.getBoolean(PREF_USE_SCHEDULED, false);
		 mScheduleCheckBox.setChecked(mUseScheduled);
		 
		 mScheduleTimePicker.setCurrentHour( mPrefs.getInt(PREF_USE_SCHEDULED_HOUR, 0));
		 mScheduleTimePicker.setCurrentMinute( mPrefs.getInt(PREF_USE_SCHEDULED_MINUTE, 1));
		 
		 mScheduleTimePicker.setIs24HourView( DateFormat.is24HourFormat(this) );
		 
		 setChangeText(mUseScheduled);
		 
		 String sdstate = Environment.getExternalStorageState();
		 LinearLayout warning = (LinearLayout)findViewById(R.id.warningLinearLayout);
		 if( sdstate.equals(Environment.MEDIA_MOUNTED) || sdstate.equals(Environment.MEDIA_MOUNTED_READ_ONLY) ){			 
			 warning.setVisibility(View.INVISIBLE);
		 }else{
			 warning.setVisibility(View.VISIBLE);			 
		 }
	}


	private void setChangeText(boolean scheduled){
		 TextView changeText = (TextView)findViewById(R.id.changeIntervalTextView);
		 if(scheduled){			 			
			 changeText.setText(R.string.scheduled);
			 mScheduleTimePicker.setIs24HourView( DateFormat.is24HourFormat(this) );
		 }else{
			 changeText.setText(R.string.change_interval);
			 mScheduleTimePicker.setIs24HourView( true );
		 }		
	}
	
	private void writeSettings(){
		mEditor.putBoolean(PREF_ACTIVATED, mActivated);
		mEditor.putString(PREF_FROM, mFromDir);
		mEditor.putBoolean(PREF_RESIZE, mResize);
		mEditor.putInt(PREF_FROM_SPINNER_INDEX, mFromIndex);
		mEditor.putBoolean(PREF_USE_SCHEDULED, mUseScheduled);
		mEditor.putInt(PREF_USE_SCHEDULED_HOUR, mScheduleTimePicker.getCurrentHour());
		mEditor.putInt(PREF_USE_SCHEDULED_MINUTE, mScheduleTimePicker.getCurrentMinute());		
		mEditor.putBoolean(PREF_SCALE_DOWN, mScaleDown);
		mEditor.commit();
	}


	@Override
	public void onBackPressed() {
		if(mWasActive){
			final Context context = BISConfigure.this;
	        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
	        BISProvider.updateAppWidget(context, appWidgetManager, mAppWidgetId);

	        Intent resultValue = new Intent();
	        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
	        setResult(RESULT_OK, resultValue);
		}
			
		super.onBackPressed();
	}
}
